<script setup lang="ts">
import { updateAvatarAPI, updateUserInfoAPI } from '@/api'
import { userAreaData, useUserInfo } from '@/composable'
import type { H5AreaData } from '@/types'
import type { AreaItem } from '@/types/user'
import { areaList } from '@vant/area-data'
import b64toBlob from 'b64-to-blob'
import type { ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'

const showSheet = ref(false)
const showSelectBirthday = ref(false)
const showSelectProfession = ref(false)
const showSelectCity = ref(false)
const { cityData } = userAreaData()
const { userInfo } = useUserInfo()
const actions = [{ name: '拍照' }, { name: '相册' }]
const maxDate = new Date('2015-01-01') // 最大时间
const minDate = new Date('1970-01-01') // 最小时间
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]

const onSelectPhoto = async (action: ActionSheetAction, index: number) => {
  if (index === 0 || index === 1) {
    const avatar = await window.hdm.openGallery() // 得到base64
    userInfo.value.avatar = `data:image/png;base64,${avatar}`
  }
}
// 确认选择生日
const confirmBirthDay = (event: { selectedValues: string[] }) => {
  userInfo.value.birthday = event.selectedValues.join('-')
  // 记录之前选择生日
  showSelectBirthday.value = false // 关闭弹层
}
// 确认选择城市

const confirmCity = (event: { selectedValues: string[]; selectedOptions: AreaItem[] }) => {
  userInfo.value.provinceCode = event.selectedValues[0] // 省编码
  userInfo.value.cityCode = event.selectedValues[1] // 市编码
  userInfo.value.countyCode = event.selectedValues[2] // 区编码
  userInfo.value.fullLocation = `${event.selectedOptions[0].text} ${event.selectedOptions[1].text} ${event.selectedOptions[2].text}`
  showSelectCity.value = false
} // 选择职业
const confirmProfession = (event: { selectedValues: string[] }) => {
  userInfo.value.profession = event.selectedValues[0]
  showSelectProfession.value = false
}
// 保存
const saveBtn = async () => {
  const key = await window.hdm.showLoading('信息保存中')
  // 判断头像是否需要上传
  if (
    !userInfo.value.avatar.startsWith('http://') &&
    !userInfo.value.avatar.startsWith('https://')
  ) {
    // 此时需要上传
    // window.hdm.showMessage('此时需要上传')
    const data = new FormData() // 空的formData对象
    // base64 -> blob
    const pureBase64 = userInfo.value.avatar.replace('data:image/png;base64,', '') // 得到纯净的base64
    const blob = b64toBlob(pureBase64, 'image/png') // 得到blob对象
    data.append('file', blob, Date.now() + '.png') // 往formData中追加数据
    // data.append(
    //   'file',
    //   b64toBlob(userInfo.value.avatar.replace('data:image/png;base64,', ''), 'image/png'),
    //   Date.now() + '.png',
    // )
    //  b64toBlob(base64字符串，文件类型)
    // base64显示的时候 加了前缀 转化的时候 要把显示的前缀去掉
    await updateAvatarAPI(data)
  }
  await updateUserInfoAPI(userInfo.value)
  window.hdm.closeLoading(key) // 关闭弹层
  window.hdm.showMessage('更新成功')
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="
          userInfo.avatar ||
          'https://foruda.gitee.com/avatar/1716533299289369832/5539886_yjh8866_1716533299.png'
        "
      >
      </van-image>
      <div class="avatar-btn" @click="showSheet = true">
        <span>修改头像</span>
      </div>
    </div>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" readonly v-model:model-value="userInfo.account"></van-field>
      <van-field
        label="昵称"
        placeholder="请输入昵称"
        v-model:model-value="userInfo.nickname"
      ></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model:model-value="userInfo.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        @click="showSelectBirthday = true"
        label="生日"
        readonly
        placeholder="请选择日期"
        v-model:model-value="userInfo.birthday"
      ></van-field>
      <van-field
        label="所在地"
        @click="showSelectCity = true"
        readonly
        placeholder="请选择所在地"
        v-model:model-value="userInfo.fullLocation"
      ></van-field>
      <van-field
        v-model="userInfo.profession"
        label="职业"
        @click="showSelectProfession = true"
        readonly
        placeholder="请选择职业"
      ></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button @click="saveBtn" class="submit_button" round block type="primary">
        保存资料
      </van-button>
    </div>
    <van-action-sheet
      v-model:show="showSheet"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelectPhoto"
    />
    <!-- 放置生日弹层 -->
    <van-popup v-model:show="showSelectBirthday" position="bottom">
      <!-- 日期选择器 -->
      <van-date-picker
        @cancel="showSelectBirthday = false"
        @confirm="confirmBirthDay"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
    <!-- 职业弹层 -->
    <van-popup v-model:show="showSelectProfession" position="bottom">
      <!-- 职业选择器 -->
      <van-picker
        @cancel="showSelectProfession = false"
        @confirm="confirmProfession"
        title="职业"
        :columns="columns"
      ></van-picker>
    </van-popup>
    <!-- 地区弹层 -->
    <van-popup v-model:show="showSelectCity" position="bottom">
      <!-- 地区选择器 -->
      <van-area
        @cancel="showSelectCity = false"
        @confirm="confirmCity"
        title="选择地区"
        :area-list="cityData"
      ></van-area>
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.submit_button {
  background-color: var(--mk-black);
  border-color: var(--mk-black);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

/* ::v-deep 通过深度选择器修改组件库的样式 */
.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
